<template>
    <div class="auction-list-container">
        <h2>拍卖列表</h2>

        <div class="search-form">
            <el-form :inline="true" :model="searchForm" ref="searchFormRef">
                <el-form-item label="商品名称">
                    <el-input v-model="searchForm.title" placeholder="请输入商品名称"></el-input>
                </el-form-item>
                <el-form-item label="分类">
                    <el-select v-model="searchForm.categoryId" placeholder="请选择分类" clearable>
                        <el-option v-for="item in categoryOptions" :key="item.value" :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <div class="auction-cards" v-loading="loading">
            <el-empty description="暂无拍卖商品" v-if="auctionList.length === 0"></el-empty>

            <div class="card-list">
                <el-card v-for="item in auctionList" :key="item.id" class="auction-card">
                    <div class="auction-image">
                        <img :src="item.image || 'https://via.placeholder.com/300x200'" alt="拍品图片" />
                    </div>
                    <div class="auction-info">
                        <h3 class="auction-title">{{ item.title }}</h3>
                        <div class="auction-price">
                            <span class="label">当前价:</span>
                            <span class="price">￥{{ item.startPrice }}</span>
                        </div>
                        <div class="auction-time">
                            <span class="label">结束时间:</span>
                            <span>{{ formatDate(item.endTime) }}</span>
                        </div>
                        <div class="auction-status">
                            <el-tag :type="getAuctionStatusType(item.status)">
                                {{ getAuctionStatusText(item.status) }}
                            </el-tag>
                        </div>
                    </div>
                    <div class="auction-actions">
                        <el-button type="primary" @click="viewAuctionDetail(item.id)">查看详情</el-button>
                    </div>
                </el-card>
            </div>
        </div>

        <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
                :page-sizes="[12, 24, 36, 48]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="total"></el-pagination>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getAuctionsByCategory } from '@/api/auction'
import { getUserCategoryList } from '@/api/category'

const router = useRouter()
const loading = ref(false)
const auctionList = ref([])
const page = ref(1)
const pageSize = ref(12)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
    title: '',
    categoryId: ''
})

const searchFormRef = ref(null)

// 分类选项
const categoryOptions = ref([])

// 获取分类列表
const fetchCategories = async () => {
    try {
        const res = await getUserCategoryList()
        if (res && Array.isArray(res)) {
            categoryOptions.value = res.map(item => ({
                value: item.id,
                label: item.name
            }))
        } else {
            console.error('获取分类列表返回格式不正确', res)
            categoryOptions.value = []
        }
    } catch (error) {
        console.error('获取分类列表失败', error)
        categoryOptions.value = []
    }
}

// 获取拍卖列表
const fetchAuctionList = async () => {
    loading.value = true
    try {
        const params = {
            page: page.value,
            pageSize: pageSize.value
        };

        // 只有在有值时才添加title参数
        if (searchForm.title && searchForm.title.trim() !== '') {
            params.title = searchForm.title.trim();
        }

        // 发送请求时直接传入categoryId，由API方法内部判断是否添加此参数
        const res = await getAuctionsByCategory(searchForm.categoryId, params);

        if (res && Array.isArray(res)) {
            auctionList.value = res;
            total.value = res.length; // 如果后端返回总数，应该使用后端返回的总数
        } else {
            auctionList.value = [];
            total.value = 0;
        }
    } catch (error) {
        console.error('获取拍卖列表失败', error);
        ElMessage.error('获取拍卖列表失败，请稍后再试');
        auctionList.value = [];
        total.value = 0;
    } finally {
        loading.value = false;
    }
}

// 查看拍卖详情
const viewAuctionDetail = (auctionId) => {
    router.push(`/market/auction/${auctionId}`)
}

// 获取拍卖状态对应的Tag类型
const getAuctionStatusType = (status) => {
    const statusMap = {
        'PENDING': 'info',
        'ACTIVE': 'success',
        'FINISHED': 'warning',
        'CANCELLED': 'danger'
    }
    return statusMap[status] || 'info'
}

// 获取拍卖状态文本
const getAuctionStatusText = (status) => {
    const statusMap = {
        'PENDING': '即将开始',
        'ACTIVE': '正在进行',
        'FINISHED': '已结束',
        'CANCELLED': '已取消'
    }
    return statusMap[status] || '未知'
}

// 格式化日期
const formatDate = (dateStr) => {
    if (!dateStr) return '未知'
    const date = new Date(dateStr)
    return date.toLocaleString()
}

// 搜索
const handleSearch = () => {
    page.value = 1
    fetchAuctionList()
}

// 重置搜索
const resetSearch = () => {
    searchFormRef.value.resetFields()
    page.value = 1
    fetchAuctionList()
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val
    fetchAuctionList()
}

const handleCurrentChange = (val) => {
    page.value = val
    fetchAuctionList()
}

onMounted(() => {
    fetchCategories()
    fetchAuctionList()
})
</script>

<style scoped>
.auction-list-container {
    padding: 20px;
}

.search-form {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
}

.auction-cards {
    margin-top: 20px;
}

.card-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 20px;
}

.auction-card {
    display: flex;
    flex-direction: column;
    height: 100%;
}

.auction-image {
    width: 100%;
    height: 200px;
    overflow: hidden;
}

.auction-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.auction-info {
    flex: 1;
    padding: 10px 0;
}

.auction-title {
    font-size: 16px;
    margin-bottom: 10px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.auction-price,
.auction-time {
    margin-bottom: 8px;
    font-size: 14px;
}

.label {
    color: #666;
    margin-right: 5px;
}

.price {
    color: #f56c6c;
    font-weight: bold;
}

.auction-status {
    margin-top: 10px;
}

.auction-actions {
    display: flex;
    justify-content: center;
    margin-top: 10px;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}
</style>